package com.yjhealth.libs.core.utils;

import android.app.Activity;
import android.app.AppOpsManager;
import android.app.Fragment;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Binder;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;

/**
 * 检查获取权限
 */
public class PermissionUtil {
    public static final int REQUEST_PERMISSIONS = 0x001;

    public static final int CONTEXT_ACTIVITY = 1;
    public static final int CONTEXT_FRAGMENT = 2;
    public static final int CONTEXT_SUPPORT_FRAGMENT = 3;

    /**
     * 检查是否有权限
     *
     * @param context
     * @param permissions
     * @return
     */
    public static boolean checkPermission(@NonNull Context context, @NonNull String[] permissions) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        ArrayList<String> needQuestPer = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            if (context.getPackageManager().checkPermission(permissions[i]
                    , context.getPackageName())
                    != PackageManager.PERMISSION_GRANTED) {
                needQuestPer.add(permissions[i]);
            }
        }

        if (needQuestPer.size() == 0) {
            return true;
        }

        return false;
    }

    /**
     * 检查是否有权限
     *
     * @param context
     * @param permissions
     * @return
     */
    public static boolean checkPermission2(@NonNull Context context, @NonNull String... permissions) {
        ArrayList<String> needQuestPer = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            if (context.getPackageManager().checkPermission(permissions[i]
                    , context.getPackageName())
                    != PackageManager.PERMISSION_GRANTED) {
                needQuestPer.add(permissions[i]);
            }
        }

        if (needQuestPer.size() == 0) {
            return true;
        }

        return false;
    }

    /**
     * 获取权限
     *
     * @param context
     * @param permissions
     * @param requestCode
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public static boolean requestPermission(@NonNull Object context, String[] permissions, int requestCode) {
        final int contextType;
        Context finalContext;

        if (context instanceof Activity) {
            contextType = CONTEXT_ACTIVITY;
            finalContext = (Activity) context;
        } else if (context instanceof Fragment) {
            contextType = CONTEXT_FRAGMENT;
            finalContext = ((Fragment) context).getActivity();
        } else if (context instanceof android.support.v4.app.Fragment) {
            contextType = CONTEXT_SUPPORT_FRAGMENT;
            finalContext = ((android.support.v4.app.Fragment) context).getActivity();
        } else {
            throw new IllegalArgumentException("context not found");
        }

        ArrayList<String> needQuestPer = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            if (finalContext.getPackageManager().checkPermission(permissions[i]
                    , finalContext.getPackageName())
                    != PackageManager.PERMISSION_GRANTED) {
                needQuestPer.add(permissions[i]);
            }
        }

        if (needQuestPer.size() != 0) {
            String[] Questper = new String[needQuestPer.size()];
            for (int i = 0; i < needQuestPer.size(); i++) {
                Questper[i] = needQuestPer.get(i);
            }

            if (contextType == CONTEXT_ACTIVITY) {
                ((Activity) context).requestPermissions(Questper, requestCode);
            } else if (contextType == CONTEXT_FRAGMENT) {
                ((Fragment) context).requestPermissions(Questper, requestCode);
            } else if (contextType == CONTEXT_SUPPORT_FRAGMENT) {
                ((android.support.v4.app.Fragment) context).requestPermissions(Questper, requestCode);
            }
            return false;
        } else {
            return true;
        }
    }

    /**
     * 权限是否都开通
     *
     * @param grantResults
     * @return
     */
    public static boolean checkSharePermission(int[] grantResults) {
        boolean check = true;
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                check = false;
                break;
            }
        }

        return check;
    }

    /**
     * 检查是否开启悬浮框功能
     * <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
     * @param context
     * @return
     */
    public static boolean checkFloatPermission(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
            return true;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            try {
                Class cls = Class.forName("android.content.Context");
                Field declaredField = cls.getDeclaredField("APP_OPS_SERVICE");
                declaredField.setAccessible(true);
                Object obj = declaredField.get(cls);
                if (!(obj instanceof String)) {
                    return false;
                }
                String str2 = (String) obj;
                obj = cls.getMethod("getSystemService", String.class).invoke(context, str2);
                cls = Class.forName("android.app.AppOpsManager");
                Field declaredField2 = cls.getDeclaredField("MODE_ALLOWED");
                declaredField2.setAccessible(true);
                Method checkOp = cls.getMethod("checkOp", Integer.TYPE, Integer.TYPE, String.class);
                int result = (Integer) checkOp.invoke(obj, 24, Binder.getCallingUid(), context.getPackageName());
                return result == declaredField2.getInt(cls);
            } catch (Exception e) {
                return false;
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                AppOpsManager appOpsMgr = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
                if (appOpsMgr == null)
                    return false;
                int mode = appOpsMgr.checkOpNoThrow("android:system_alert_window", android.os.Process.myUid(), context
                        .getPackageName());
                return mode == AppOpsManager.MODE_ALLOWED || mode == AppOpsManager.MODE_IGNORED;
            } else {
                return Settings.canDrawOverlays(context);
            }
        }
    }
}
